package com.clothing.customization.controller;

import com.clothing.customization.common.ApiResponse;
import com.clothing.customization.entity.ImageFile;
import com.clothing.customization.service.ImageFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/upload")
@RequiredArgsConstructor
@CrossOrigin(origins = "*", allowedHeaders = "*", exposedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE, RequestMethod.OPTIONS})
@Slf4j
public class FileController {
    
    private final ImageFileService imageFileService;
    
    /**
     * 通用文件上传接口
     *
     * @param file 上传的文件
     * @param module 模块名称，可选
     * @param relationId 关联ID，可选
     * @return 文件访问URL
     */
    @PostMapping("")
    public ApiResponse<String> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "module", required = false, defaultValue = "common") String module,
            @RequestParam(value = "relationId", required = false, defaultValue = "0") Long relationId,
            HttpServletRequest request) {
        
        log.info("==== 通用文件上传接口被调用 ====");
        log.info("接收到文件上传请求: filename={}, contentType={}, size={}, module={}, relationId={}", 
                file.getOriginalFilename(), file.getContentType(), file.getSize(), module, relationId);
        log.info("请求来源: {}", request.getRemoteAddr());
        log.info("请求头: {}", request.getHeaderNames());
        
        if (file.isEmpty()) {
            log.warn("上传的文件为空");
            return ApiResponse.error("上传失败，请选择文件");
        }
        
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return ApiResponse.error("只允许上传图片文件");
        }
        
        try {
            // 上传文件并保存元数据
            ImageFile imageFile = imageFileService.uploadImage(file, module, relationId);
            
            // 返回文件访问URL
            log.info("文件上传成功: {}", imageFile.getAccessUrl());
            return ApiResponse.success(imageFile.getAccessUrl());
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return ApiResponse.error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取指定模块下的图片列表
     *
     * @param module 模块名称
     * @param relationId 关联ID
     * @return 图片列表
     */
    @GetMapping("/images")
    public ApiResponse<List<ImageFile>> getImages(
            @RequestParam("module") String module,
            @RequestParam("relationId") Long relationId) {
        
        List<ImageFile> images = imageFileService.getImagesByModuleAndRelationId(module, relationId);
        return ApiResponse.success(images);
    }
    
    /**
     * 删除图片
     *
     * @param id 图片ID
     * @return 删除结果
     */
    @DeleteMapping("/images/{id}")
    public ApiResponse<Boolean> deleteImage(@PathVariable Long id) {
        boolean result = imageFileService.deleteImage(id);
        return result 
                ? ApiResponse.success(true) 
                : ApiResponse.error("删除失败");
    }
} 